'use strict';
const crypto = require('crypto');
const stream = require('stream');
const Service = require('egg').Service;

class bufferService extends Service {
  // 复制流
  async index(stream) {
    return new Promise(resolve => {
      const buffers = [];
      stream.on('data', data => {
        buffers.push(data);
      });
      stream.on('end', async () => {
        resolve(Buffer.concat(buffers));
      });
    });
  }
  // buffer 转 stream
  async buffertoStream(buffer) {
    return new Promise(async resolve => {
      const bufferStream = new stream.PassThrough();
      bufferStream.end(buffer);
      await bufferStream.pipe(process.stdout);
      bufferStream.on('finish', () => {
        resolve(bufferStream);
      });
    });
  }
  // buffer生成hash
  async buffertoHash(stream) {
    return new Promise(async resolve => {
      const fsHash = crypto.createHash('md5');
      fsHash.update(stream, 'utf8');
      const md5 = fsHash.digest('hex');
      resolve(md5);
      // stream.on('data', d => {
      //   fsHash.update(d);
      // });
      // stream.on('end', () => {
      //   const md5 = fsHash.digest('hex');
      //   resolve(md5);
      // });
    });
  }
}

module.exports = bufferService;
